import Vue from "vue";
import VueRouter from "vue-router";
import { getToken } from "@/utils/token.js";

Vue.use(VueRouter);

import login from "@/views/user/login.vue";
import home from "@/views/home/home.vue";
import qa from "@/views/qa/qa.vue";
import movie from "@/views/movie/movie.vue";
import user from "@/views/user/user.vue";
import edit from "@/views/user/edit.vue";
import student from "@/views/user/student.vue";
import notfound from "@/views/notfound/notfound.vue";
import article from "@/views/home/article.vue";
import search from "@/views/home/search.vue";
import searchResult from "@/views/home/searchResult.vue";

const routes = [
  {
    path: "/login",
    name: "login",
    component: login
  },
  {
    path: "/home",
    name: "home",
    component: home,
    meta: {
      showTab: true
    }
  },
  {
    path: "/qa",
    name: "qa",
    component: qa,
    meta: {
      showTab: true
    }
  },
  {
    path: "/movie",
    name: "movie",
    component: movie,
    meta: {
      showTab: true
    }
  },
  {
    path: "/user",
    name: "user",
    component: user,
    meta: {
      showTab: true, //是否需要渲染导航栏
      isLogin: true
    }
  },
  {
    path: "/notfound",
    name: "notfound",
    component: notfound
  },
  {
    path: "/edit",
    name: "edit",
    component: edit
  },
  {
    path: "/article",
    name: "myarticle",
    component: article
  },
  {
    path: "/student",
    name: "student",
    component: student
  },
  {
    path: "/search",
    name: "search",
    component: search
  },
  {
    path: "/searchResult",
    name: "searchResult",
    component: searchResult
  },
  {
    path: "/",
    redirect: "/home"
  },
  {
    path: "*",
    redirect: "/notfound"
  }
];

// 要想实例用到，得在实例化之前修改
// 先用一个变量保存着原生的push方法
const originPush = VueRouter.prototype.push;

VueRouter.prototype.push = function(location, onResolve, onReject) {
  if (onResolve || onReject) {
    // 如果用户有传入这两个处理函数，则正常执行
    return originPush.call(this, location, onResolve, onReject);
  } else {
    //如果用户没有传入这两个处理函数，则我们帮他不抛出错误
    return originPush.call(this, location).catch(err => {});
  }
};

const router = new VueRouter({
  routes,
  mode: "history"
});

router.beforeEach((to, from, next) => {
  //${to and from are Route Object,next() must be called to resolve the hook}

  if (to.meta.isLogin && !getToken()) {
    next({ path: "/login" });
  } else {
    next();
  }
});

export default router;
